const thor_util = require('../../utils/thor_util')
const app = getApp();
const request = require('../../utils/request.js');
const config = require('../../utils/config');
const util = require('../../utils/util');

Page({
  data: {
    loadding: false,
    show: false,
    bottom: 0,
    open_listen: false, // 是否打开websocket监听
    finish_load: false, // 页面是否完成加载（主要作用是socket前预备标识）
    socket: null, // websocket对象
    watcherIndex: null, // 监听器下标
    targetUid: null, // 当前聊天对象uid
    selfUid: null,// 自己uid
    msgCount: 20, // 默认拉取的消息数
    chatList: [], // 聊天消息列表
    targetUserInfo: null, // 当前聊天对象信息
    selfUserInfo: null, // 用户自己的信息
    isFocus: false,
    clearValue: "",
  },

  onLoad: function (options) {
    // 获取用户信息
    let targetUid = options.target_uid;
    let selfUid = wx.getStorageSync("userInfo").uid;
    this.getUserInfo(targetUid, false);
    this.getUserInfo(selfUid, true);
    // 获取websocket对象
    let socket = app.getWebSocketTask();
    // 设置全局websocket处理器不处理该uid的信息（因为当前页面会注册新的处理器）
    app.$notify.setNotHandleUid(targetUid);
    this.setData({
      socket: socket,
      finish_load: true,
      targetUid: targetUid,
      selfUid: selfUid
    });
    // 获取缓存最后的chatId，拉取历史聊天记录，跟websocket收到的消息重排序，防止消息乱序
    let chatId = wx.getStorageSync('lastChat:' + targetUid);
    let type = null;
    if (chatId) {
      type = 1;
    }
    this.getHistoryMsgList(chatId, type); // 这一步之后，新来的websocket消息如果id大于历史最大id则直接尾插，不再排序
  },

  onShow: function(options) {
    this.onMessage();
  },

  // 页面返回事件
  onUnload: function() {
    app.$notify.delWatcher(this.data.watcherIndex);
    app.$notify.setNotHandleUid(null);
    this.setData({
      watcherIndex: null
    });
    console.log('关闭页面监听的websocket');
  },

  // 获取用户信息
  getUserInfo: function(uid, self) {
    let that = this;
    let url = config.SERVER_URL + 'index/user/' + uid;
    wx.showLoading({
      title: '加载ing'
    })
    request.requestGetApi(url, {}, {}, 'application/json').then(res => {
      if (res.status === config.STATUS_OK) {
        if (self) {
          that.setData({
            selfUserInfo: res.data
          });
        } else {
          that.setData({
            targetUserInfo: res.data
          })
          // 设置bar
          wx.setNavigationBarTitle({
            title: this.data.targetUserInfo.nickname
          })
        }
      }
    }).catch(err => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    });
  },

  // 获取历史聊天记录
  getHistoryMsgList: function(chatId, type) {
    let that = this;
    let targetUid = this.data.targetUid;
    let count = this.data.msgCount;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'chat/list/chat/history/single';
    let params = {
      targetUid: targetUid,
      chatId: chatId,
      type: type,
      count: count
    }
    wx.showLoading({
      title: '加载ing'
    });
    request.requestPostApi(url, token, params, 'application/json').then((res) => {
      if(res.status === config.STATUS_OK){
        // todo 还有重排序等操作
        console.log("获取到的聊天消息：" + res.data);
        that.setData({
          chatList: res.data
        });
        // 调整窗口浮动
        wx.onKeyboardHeightChange(res => {
          this.setData({
            bottom: res.height
          });
        });
        // 打开websocket监听
        this.onMessage();
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  onPageScroll(e) {
    // 上滑到顶加载更多
    if (e.scrollTop == 0 && !this.data.loadding) {
      this.setData({
        loadding: true
      }, () => {
        setTimeout(() => {
          this.setData({
            show: true,
            loadding: false
          })
        }, 1000)
      })
    }
  },

  // 判断消息是否当前页面处理
  msgSupport: function(type) {
    let msgType = config.MSG_TYPE;
    if(
        type == msgType.SINGLE_TEXT_MSG.type ||
        type == msgType.SINGLE_IMG_MSG.type ||
        type == msgType.SERVER_ACK.type
      ) {
        return true;
      }
      return false;
  },

  // 监听消息
  onMessage: function() {
    let that = this;
    if (!this.data.open_listen && this.data.finish_load) {
      let watcherIndex = app.$notify.addWatcher(that.handleMessage, that);
      this.setData({
        watcherIndex: watcherIndex,
        open_listen: true,
        socket: app.$notify.socketTask
      });
    }
  },

  // 处理消息
  handleMessage: function(data, pageObj) {
    if (
        this.data.open_listen &&
        (
          (data.toUid == this.data.selfUid && data.fromUid == this.data.targetUid) ||
          (data.fromUid == this.data.selfUid && data.toUid == this.data.targetUid)
        )
    ) {
      // none
    } else {
      return
    }
    let type = data.type;
    let chatId = data.id;
    if (type && this.msgSupport(type)) {
      this.setData({
        chatList: this.data.chatList.concat([data])
      })
      this.pageScrollToBottom();
      console.log("页面监听消息，id:" + chatId + "，内容:" + data.content);
    }
    app.$notify.ack(chatId, pageObj.data.targetUid);
  },

  // 文本框聚焦回调
  focusInput() {
    this.setData({
      isFocus: true
    });
  },

  // 文本框取消聚焦回调
  blurInput() {
    let that = this;
    setTimeout(function() {
      that.setData({
        isFocus: false
      })
    }, 200);
  },

  // 发送文本消息
  sendTextMsg(e) {
    if(!app.checkedUserLoading()){
      return;
    }
    let params = e.detail.value;
    if(typeof params !== 'object'){
      let content = params;
      params = { content };
    }
    params.type = config.MSG_TYPE.SINGLE_TEXT_MSG.type;
    params.toUid = this.data.targetUid;
    params.timeStamp = new Date().getTime().toString();
    let msg = JSON.stringify(params);
    this.sendMsg(msg);
  },

  // 发送消息
  sendMsg(msg) {
    let that = this;
    // todo 成功和失败都要重试
    this.data.socket.send({
      data: msg,
      success: function (res) {
        console.log("发送消息成功，消息内容：" + msg);
        that.setData({
          clearValue: ""
        });
      },
      fail: function (res) {
        console.warn("发送消息失败，消息内容：" + msg)
      }
    })
  },

  // 获取容器高度，使页面滚动到容器底部
  pageScrollToBottom: function() {
    wx.createSelectorQuery().select('#chat_panel').boundingClientRect(function(rect) {
      if (rect){
        // 使页面滚动到底部
        console.log(rect.height);
        wx.pageScrollTo({
           scrollTop: rect.height
        })
      }
    }).exec()
  },
})